package com.example.springbootmodel.jdbc.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/jdbc")
public class JDBCAction {

    @Autowired
    JdbcTemplate jdbcTemplate;

    // 增
    @GetMapping("/addUser")
    public String addUser(){
        int i = jdbcTemplate.update("insert into user(id,name,pwd) values (2,'jdbc','123456')");
        if(i > 0){
            return "成功";
        }
        return "失败";
    }

    // 删
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        int i = jdbcTemplate.update("delete from user where id = ?",id);
        if(i > 0){
            return "成功";
        }
        return "失败";
    }

    // 改
    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id){
        Object[] o = new Object[]{"小明2","1323",id};
        int i = jdbcTemplate.update("update user set name = ?,pwd = ? where id = ?",o);
        if(i > 0){
            return "成功";
        }
        return "失败";
    }

    // 查
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        return jdbcTemplate.queryForList("select * from user");
    }

}
